package org.deng.learn.sse;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 邓力宾
 * @date 2020/12/18 14:50
 * @desc 测试sse(Server Send Event)
 */
@WebServlet("/demo")
public class DemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/event-stream;charset=UTF-8");
        for(int i = 0; i < 5; i++){
            //指定事件标识
            resp.getWriter().write("event:e\n");
            //格式: data: + 数据 + 2个回车
            resp.getWriter().write("data:data-"+i+"\n\n");
            resp.getWriter().flush(); //多次返回数据
            try {
                //模拟耗时
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
